package com.kim.authorization.server.controller;

import com.kim.oauth.common.constants.Oauth2ExceptionEnum;
import com.kim.common.utilcom.model.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationDetails;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * UserAccountController
 */
@Api(tags = {"app: 用户账户相关", "检查是否授权"})
@Slf4j
@RestController
@RequestMapping("/app/v1/user")
public class LogOutController {

    /**
     * tokenStore
     */
    @Resource
    private TokenStore tokenStore;

    /**
     * 用户登出
     * 登出移除access_token和refresh_token
     */
    @ApiOperation(value = "用户登出")
    @PostMapping(value = "/logout")
    public Result removeToken() {

        // 拿到当前用户信息
        Authentication user = SecurityContextHolder.getContext().getAuthentication();
        // 令牌
        String accessTokenValue = null;
        if (user != null) {
            if (user instanceof OAuth2Authentication) {
                OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails) user.getDetails();
                accessTokenValue = details.getTokenValue();
            }
        }
        // 未知异常
        if (null == accessTokenValue) {
            return Result.failed(Oauth2ExceptionEnum.UNKNOWN_LOGOUT_ERR.getCode(), Oauth2ExceptionEnum.UNKNOWN_LOGOUT_ERR.getMsg());
        }
        //确认token存在
        OAuth2AccessToken accessToken = tokenStore.readAccessToken(accessTokenValue);
        if (accessToken != null) {
            // 移除access_token
            tokenStore.removeAccessToken(accessToken);

            // 移除refresh_token
            if (accessToken.getRefreshToken() != null) {
                tokenStore.removeRefreshToken(accessToken.getRefreshToken());
            }

        }
        log.info("用户登出");
        return Result.succeed();
    }
}
